package org.lc.stk.service.bank.impl;

import org.lc.stk.model.banks.Bank;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.lc.stk.dao.bank.PaperBankRepository;
import org.lc.stk.model.banks.PaperBank;
import org.lc.stk.model.paper.attr.PaperTemplate;
import org.lc.stk.model.question.attrs.DifficultySchema;
import org.lc.stk.model.question.attrs.QuestionType;
import org.lc.stk.service.bank.PaperBankService;
import org.lc.stk.service.exception.BusinessException;
import org.lc.stk.service.paper.PaperTemplateService;
import org.lc.stk.web.dto.bank.PaperBankDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PaperBankServiceImpl implements PaperBankService {

    @Autowired
    private PaperBankRepository bankRepository;

    @Autowired
    private PaperTemplateService paperTemplateService;

    @Override
    @Transactional
    public PaperBank create(PaperBankDTO dto) {
        // 验证名称是否重复
        if (bankRepository.existsByNameAndIdNot(dto.getName(), null)) {
            throw new BusinessException("已存在同名试卷库");
        }

        PaperBank bank = new PaperBank();
        bank.setName(dto.getName());
        bank.setState(dto.getState() == 1 ? Bank.BankState.ACTIVE : Bank.BankState.INACTIVE);

        // 设置试卷模板
        if (dto.getPaperTemplateIds() != null && dto.getPaperTemplateIds().length > 0) {
            List<PaperTemplate> templates = Arrays.stream(dto.getPaperTemplateIds())
                .map(id -> {
                    PaperTemplate template = paperTemplateService.findById(id);
                    if (template == null) {
                        throw new BusinessException("试卷模板不存在: " + id);
                    }
                    return template;
                })
                .collect(Collectors.toList());
            bank.setPaperTemplates(templates);
        }

        if (dto.getQuestionTypeIds() != null) {
            List<QuestionType> questionTypes = dto.getQuestionTypeIds().stream()
                .map(this::getQuestionType)
                .collect(Collectors.toList());
            bank.setQuestionTypes(questionTypes);
        }

        if (dto.getDifficultySchemaId() != null) {
            DifficultySchema schema = getDifficultySchema(dto.getDifficultySchemaId());
            bank.setDifficultySchema(schema);
        }

        return bankRepository.save(bank);
    }

    @Override
    @Transactional
    public PaperBank update(Integer id, PaperBankDTO dto) {
        PaperBank bank = getById(id);
        if (bank == null) {
            throw new BusinessException("试卷库不存在");
        }

        // 验证名称是否重复
        if (bankRepository.existsByNameAndIdNot(dto.getName(), id)) {
            throw new BusinessException("已存在同名试卷库");
        }

        bank.setName(dto.getName());
        bank.setState(dto.getState() == 1 ? Bank.BankState.ACTIVE : Bank.BankState.INACTIVE);

        // 更新试卷模板
        if (dto.getPaperTemplateIds() != null) {
            List<PaperTemplate> templates = Arrays.stream(dto.getPaperTemplateIds())
                .map(templateId -> {
                    PaperTemplate template = paperTemplateService.findById(templateId);
                    if (template == null) {
                        throw new BusinessException("试卷模板不存在: " + templateId);
                    }
                    return template;
                })
                .collect(Collectors.toList());
            bank.setPaperTemplates(templates);
        }

        if (dto.getQuestionTypeIds() != null) {
            List<QuestionType> questionTypes = dto.getQuestionTypeIds().stream()
                .map(this::getQuestionType)
                .collect(Collectors.toList());
            bank.setQuestionTypes(questionTypes);
        }

        if (dto.getDifficultySchemaId() != null) {
            DifficultySchema schema = getDifficultySchema(dto.getDifficultySchemaId());
            bank.setDifficultySchema(schema);
        }

        return bankRepository.save(bank);
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        PaperBank bank = getById(id);
        if (bank == null) {
            throw new BusinessException("试卷库不存在");
        }
        
        // TODO 是否需要验证能否删除
        bank.setState(Bank.BankState.INACTIVE); // 逻辑删除
        bankRepository.save(bank);
    }

    @Override
    public PaperBank getById(Integer id) {
        return bankRepository.findById(id)
            .orElseThrow(() -> new BusinessException("试卷库不存在"));
    }

    @Override
    public Page<PaperBank> query(
        String name, 
        Integer state, 
        Pageable pageable
    ) {
        return bankRepository.findByConditions(name, state, pageable);
    }

    @Override
    public boolean isNameExists(String name, Integer excludeId) {
        return bankRepository.existsByNameAndIdNot(name, excludeId);
    }

    @Override
    public PaperBank getByTemplateId(Integer templateId) {
        return bankRepository.findByTemplateId(templateId)
            .orElse(null);
    }

    private QuestionType getQuestionType(Integer id) {
        // TODO: 从QuestionTypeService获取题型
        throw new UnsupportedOperationException("Not implemented");
    }

    private DifficultySchema getDifficultySchema(Integer id) {
        // TODO: 从DifficultySchemaService获取难度方案
        throw new UnsupportedOperationException("Not implemented");
    }
}
